using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TCEntity;

namespace TCDbService
{
  public class CommunityService
  {
    readonly TCDbContext _context;
    readonly AccountService _account;
    readonly IServiceProvider _provider;
    public CommunityService(TCDbContext context, IServiceProvider serviceProvider)
    {
      _context = context;
      _provider = serviceProvider;
      _account = serviceProvider.GetService<AccountService>();
    }
    public async Task JoinAsync(User user, int id)
    {
      await _account.LoginAsync(user);
      var com = await _context.Communities.FindAsync(id);
      if (com == null) throw new ArgumentException("指定的社区不存在。");
      if (await _context.Users_Communities.AnyAsync(entity => entity.Username == user.Username && entity.CommunityId == com.Id))
        throw new ArgumentException("已加入该社区。");
      _context.Add(new User_Community()
      {
        Username = user.Username,
        CommunityId = com.Id
      });
      await _context.SaveChangesAsync();
    }
    public async Task<Community> SearchAsync(User user, string communityName)
    {
      await _account.LoginAsync(user);
      var community = await _context.Communities.FirstAsync(entity => entity.Name == communityName);
      if (community == null) throw new ArgumentException("未找到指定社区。");
      return community;
    }
    public async Task<List<Community>> SelectAsync(User user)
    {
      await _account.LoginAsync(user);
      var result = await _context.Users_Communities
        .Where(entity => entity.Username == user.Username)
        .Join(_context.Communities, entity => entity.CommunityId, entity => entity.Id, (_, community) => community)
        .ToListAsync();
      if (!result.Any()) throw new ArgumentException("该用户尚未加入任何社区。");
      return result;
    }
    public async Task QuitAsync(User user, int communityId)
    {
      await _provider.GetService<ShareService>().QuitAsync(user, communityId);
      var entity = await _context.FindAsync<User_Community>(user.Username, communityId);
      _context.Remove(entity);
      await _context.SaveChangesAsync();
    }
    public async Task DeleteAsync(User user)
    {
      await _account.LoginAsync(user);
      var relations = await _context.Users_Communities.Where(com => com.Username == user.Username).ToArrayAsync();
      _context.RemoveRange(relations);
      foreach (var item in relations)
      {
        var com = await _context.Communities.FindAsync(item.CommunityId);
        _context.Remove(com);
      }
      await _context.SaveChangesAsync();
    }

  }
}
